/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lbim.client.main;

import javax.microedition.location.LocationException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import lbim.client.model.Account;
import lbim.client.ui.MapCanvas;
import lbim.protocol.Controller;
import org.netbeans.microedition.lcdui.LoginScreen;

/**
 * @author Jestan
 */
public class TestMIDlet extends MIDlet implements CommandListener, ChatListener, LoginListener, PresenceListener, LogoutListener {

    private boolean midletPaused = false;
    private Controller controller;
    private Account account;
    private MapCanvas mapCanvas;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private LoginScreen loginScreen;
    private Form form;
    private TextField textField;
    private Command okCommand;
    private Command okCommand1;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The TestMIDlet constructor.
     */
    public TestMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
        account = new Account("tharindu", "123", "http://192.168.0.1:8080");
        account.setChatListener(this);
        account.setLoginListener(this);
        account.setPresenceListener(this);
        account.setLogoutListener(this);
        try {
            controller = new Controller(account);
        } catch (LocationException ex) {
            ex.printStackTrace();
        }

        mapCanvas = new MapCanvas(controller);
        account.setMapUpdateListener(mapCanvas);
        int x = mapCanvas.getWidth() + 100;
        int y = mapCanvas.getHeight() + 100;
        String mapResolution = "" + x + "x" + y;
        
        controller.setMapResolution(mapResolution); // important

//GEN-BEGIN:|0-initialize|1|0-postInitialize
        form = new Form("Chat", new Item[] { getTextField() });
        okCommand = new Command("Logout", Command.OK, 0);
        okCommand1 = new Command("Chat", Command.OK, 0);
        form.addCommand(okCommand);
        form.addCommand(okCommand1);
        form.setCommandListener(this);
//GEN-END:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getLoginScreen());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|26-preAction
            if (command == okCommand) {//GEN-END:|7-commandAction|1|26-preAction
                // write pre-action user code here
                method1();//GEN-LINE:|7-commandAction|2|26-postAction
                // write post-action user code here
            } else if (command == okCommand1) {//GEN-LINE:|7-commandAction|3|32-preAction
                // write pre-action user code here
                method2();//GEN-LINE:|7-commandAction|4|32-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|5|17-preAction
        } else if (displayable == loginScreen) {
            if (command == LoginScreen.LOGIN_COMMAND) {//GEN-END:|7-commandAction|5|17-preAction
                // write pre-action user code here
                method();//GEN-LINE:|7-commandAction|6|17-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
        }//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|8|
    //</editor-fold>//GEN-END:|7-commandAction|8|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: loginScreen ">//GEN-BEGIN:|15-getter|0|15-preInit
    /**
     * Returns an initiliazed instance of loginScreen component.
     * @return the initialized component instance
     */
    public LoginScreen getLoginScreen() {
        if (loginScreen == null) {//GEN-END:|15-getter|0|15-preInit
            // write pre-init user code here
            loginScreen = new LoginScreen(getDisplay());//GEN-BEGIN:|15-getter|1|15-postInit
            loginScreen.setLabelTexts("Username", "Password");
            loginScreen.setTitle("loginScreen");
            loginScreen.addCommand(LoginScreen.LOGIN_COMMAND);
            loginScreen.setCommandListener(this);
            loginScreen.setBGColor(-3355444);
            loginScreen.setFGColor(0);
            loginScreen.setUseLoginButton(false);
            loginScreen.setLoginButtonText("Login");//GEN-END:|15-getter|1|15-postInit
            // write post-init user code here
        }//GEN-BEGIN:|15-getter|2|
        return loginScreen;
    }
    //</editor-fold>//GEN-END:|15-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: method ">//GEN-BEGIN:|20-entry|0|21-preAction
    /**
     * Performs an action assigned to the method entry-point.
     */
    public void method() {//GEN-END:|20-entry|0|21-preAction
        // write pre-action user code here
        controller.connect();
        switchDisplayable(null, form);//GEN-LINE:|20-entry|1|21-postAction
        // write post-action user code here
    }//GEN-BEGIN:|20-entry|2|
    //</editor-fold>//GEN-END:|20-entry|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Method: method1 ">//GEN-BEGIN:|27-entry|0|28-preAction
    /**
     * Performs an action assigned to the method1 entry-point.
     */
    public void method1() {//GEN-END:|27-entry|0|28-preAction
        // write pre-action user code here
        controller.disconnect();
        switchDisplayable(null, getLoginScreen());//GEN-LINE:|27-entry|1|28-postAction
        // write post-action user code here
    }//GEN-BEGIN:|27-entry|2|
    //</editor-fold>//GEN-END:|27-entry|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: method2 ">//GEN-BEGIN:|33-entry|0|34-preAction
    /**
     * Performs an action assigned to the method2 entry-point.
     */
    public void method2() {//GEN-END:|33-entry|0|34-preAction
        // write pre-action user code here
        controller.sendChatMessage("hello", "foo");
//GEN-LINE:|33-entry|1|34-postAction
        // write post-action user code here
    }//GEN-BEGIN:|33-entry|2|
    //</editor-fold>//GEN-END:|33-entry|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">//GEN-BEGIN:|36-getter|0|36-preInit
    /**
     * Returns an initiliazed instance of textField component.
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {//GEN-END:|36-getter|0|36-preInit
            // write pre-init user code here
            textField = new TextField("Received Message:", null, 32, TextField.ANY);//GEN-LINE:|36-getter|1|36-postInit
            // write post-init user code here
        }//GEN-BEGIN:|36-getter|2|
        return textField;
    }
    //</editor-fold>//GEN-END:|36-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void messageReceived(String sender, String message) {
        textField.setString(sender+ ":" +message);
    }

    public void loginResponseReceived(int code) {
        controller.sendPresenceReqMessage();
        controller.sendLocationUpdate();
        mapCanvas.init();
        switchDisplayable(null, mapCanvas);

    }

    public void presenceResponseReceived(String presenceList) {
        System.out.println("[TestMIDlet] Presence update :"+ presenceList);
    }

    public void logoutResponseReceived(int code, String description) {
        System.out.println("[TestMIDlet] logout response received :"+ description);
    }

}
